package com.opensource.component.commom.http;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * created by zhanglong and since  2019/12/27  5:24 ����
 *
 * @description: ʹ��pool����httpclient
 */
public final class HttpClientUtils {
    private HttpClientUtils() {
    }

    public static String doGet(String url) throws IOException {
        return doGet(url, null, null);
    }

    public static String doGet(String url, Map<String, String> params,
                               CredentialsProvider provider, Header... headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = new ArrayList<>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, Charsets.UTF_8));
        }
        HttpGet httpGet = new HttpGet(url);
        if (null != headers && headers.length > 0) {
            httpGet.setHeaders(headers);
        }
        return submit(httpGet, provider);

    }

    public static String doPost(String url, Map<String, String> params,
                                CredentialsProvider provider, Header... headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        HttpPost httpPost = new HttpPost(url);
        if (null != headers && headers.length > 0) {
            httpPost.setHeaders(headers);
        }
        if (!params.isEmpty()) {
            httpPost.setEntity(new StringEntity(JSON.toJSONString(params), Charset.defaultCharset()));
        }
        return submit(httpPost, provider);
    }

    private static String submit(HttpUriRequest request, CredentialsProvider provider)
            throws IOException {
        CloseableHttpResponse response = HttpClientPool.DEFAULT
                .setDefaultCredentialsProvider(provider).fetchHttpClient()
                .execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            request.abort();
            throw new HttpResponseException(statusCode, "HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, Charsets.UTF_8);
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    }
}
